package com.swinw.asumall.ware.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.swinw.asumall.ware.entity.PurchaseDetailEntity;
import com.swinw.asumall.ware.service.PurchaseDetailService;
import com.swinw.asumall.ware.service.WareSkuService;
import com.swinw.asumall.ware.vo.MergeVo;
import com.swinw.asumall.ware.vo.PurchaseDoneVo;
import com.swinw.asumall.ware.vo.PurchaseItemDoneVo;
import com.swinw.common.constant.WareConstant;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.swinw.common.utils.PageUtils;
import com.swinw.common.utils.Query;

import com.swinw.asumall.ware.dao.PurchaseDao;
import com.swinw.asumall.ware.entity.PurchaseEntity;
import com.swinw.asumall.ware.service.PurchaseService;
import org.springframework.transaction.annotation.Transactional;


@Service("purchaseService")
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity> implements PurchaseService {

    @Autowired
    PurchaseDetailService purchaseDetailService;

    @Autowired
    WareSkuService wareSkuService;

    /**
     * {
     *    id: 123,//采购单id
     *    items: [{itemId:1,status:4,reason:""}]//完成/失败的需求详情
     * }
     * 采购人员完成采购信息
     *      1、更新采购完成的采购项状态
     *      2、更新采购单的状态
     *          2.1、如果当前采购单下的所有采购项都采购成功，那么当前的采购单状态为也完成
     *          2.2、如果当前采购单下有一个采购项不成功，那么当前的采购单状态为有异常
     *      3、修改库存信息
     *          3.1、如果仓库中存在当前采购的商品，那么就加库存
     *          3.2、如果仓库中不存在当前的采购的商品，那么就添加库存
     *              （添加库存时需要查询商品名字，即需要调用商品服务）
     * @param purchaseDoneVo
     */
    @Transactional
    @Override
    public void updatePurchaseDone(PurchaseDoneVo purchaseDoneVo) {
        //1、更新采购完成的采购项状态
        List<PurchaseItemDoneVo> items = purchaseDoneVo.getItems();
        List<PurchaseDetailEntity> detailEntities = new ArrayList<>();
        Boolean flag = true;
        for (PurchaseItemDoneVo item : items) {
            PurchaseDetailEntity detailEntity = new PurchaseDetailEntity();
            detailEntity.setId(item.getItemId());
            if(item.getStatus() == WareConstant.PurchaseDetailStatusEnum.HASERROR.getCode()){
                flag = false;
                detailEntity.setStatus(item.getStatus());
            }else{
                detailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.FINISH.getCode());
                //3、更新库存 sku_id,ware_id,
                PurchaseDetailEntity entity = purchaseDetailService.getById(item.getItemId());
                wareSkuService.addStock(entity.getSkuId(),entity.getWareId(),entity.getSkuNum());

            }
            detailEntities.add(detailEntity);
        }
        purchaseDetailService.updateBatchById(detailEntities);

        //2、修改采购单信息
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(purchaseDoneVo.getId());
        purchaseEntity.setUpdateTime(new Date());
        purchaseEntity.setStatus(flag?WareConstant.PurchaseStatusEnum.FINISH.getCode() : WareConstant.PurchaseStatusEnum.HASERROR.getCode());
        this.updateById(purchaseEntity);



    }

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        QueryWrapper<PurchaseEntity> queryWrapper = new QueryWrapper<>();
        String key = (String) params.get("key");
        if(!StringUtils.isEmpty(key)){
            queryWrapper.and((warpper)->{
                warpper.eq("id",key).or().like("assignee_name",key);
            });
        }
        String status = (String) params.get("status");

        if(!StringUtils.isEmpty(status)){
            try{
                int statu = Integer.parseInt(status);
                queryWrapper.eq("status",statu);
            }catch (Exception e){

            }
        }
        IPage<PurchaseEntity> page = this.page(
        new Query<PurchaseEntity>().getPage(params),
                queryWrapper
        );

        return new PageUtils(page);
    }

    /**
     * 查询新建的采购单和也分配的采购单
     * @return
     */
    @Override
    public PageUtils queryUnreceiveList(Map<String, Object> params) {

        QueryWrapper<PurchaseEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", 0).or()
                .eq("status",1);

        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                queryWrapper
        );

        return new PageUtils(page);
    }

    /**
     * 合并多个采购单信息
     * 如果传递了采购单Id，那就直接合并，如果没有传递，那么就先创建
     * @param mergeVo
     */
    @Override
    public void merge(MergeVo mergeVo) {
        Long purchaseId = mergeVo.getPurchaseId();
        if(purchaseId == null){//表示没有传递采购单ID
            PurchaseEntity purchaseEntity = new PurchaseEntity();
            purchaseEntity.setCreateTime(new Date());
            purchaseEntity.setUpdateTime(new Date());
            purchaseEntity.setStatus(0);
            purchaseEntity.setPriority(1);
            this.save(purchaseEntity);
            purchaseId = purchaseEntity.getId();
        }
        Long finalPurchaseId = purchaseId;
        List<PurchaseDetailEntity> collect = mergeVo.getItems().stream().map(i -> {
            PurchaseDetailEntity entity = new PurchaseDetailEntity();
            entity.setId(i);
            entity.setPurchaseId(finalPurchaseId);
            entity.setStatus(1);
            return entity;
        }).collect(Collectors.toList());

        purchaseDetailService.updateBatchById(collect);
    }

    /**
     * 领取采购单
     * 所领取的采购单必须是新建的或者是也分配的
     * 且必须是自己的采购单
     * @param ids
     */
    @Transactional
    @Override
    public void receivedPurchase(List<Long> ids) {
        List<PurchaseEntity> collect = ids.stream().map(id -> {//通过采购单Id查询出采购信息
            PurchaseEntity byId = this.getById(id);
            return byId;
        }).filter(item -> {//过滤掉状态不是新建和也分配的采购单
            if (item.getStatus() == WareConstant.PurchaseStatusEnum.CREATED.getCode() ||
                    item.getStatus() == WareConstant.PurchaseStatusEnum.ASSIGNED.getCode()) {
                return true;
            } else {
                return false;
            }
        }).map(item -> {//重新封装实体
            PurchaseEntity entity = new PurchaseEntity();
            entity.setId(item.getId());
            entity.setStatus(2);
            entity.setUpdateTime(new Date());
            return entity;
        }).collect(Collectors.toList());

        this.updateBatchById(collect);

        ids.forEach(id->{
            List<PurchaseDetailEntity> detailEntities = purchaseDetailService.getPurchaseDetailByPurchaseId(id);
            List<PurchaseDetailEntity> collect1 = detailEntities.stream().map(item -> {
                PurchaseDetailEntity entity = new PurchaseDetailEntity();
                entity.setId(item.getId());
                entity.setStatus(2);
                return entity;
            }).collect(Collectors.toList());
            purchaseDetailService.updateBatchById(collect1);
        });
    }

}